package com.tang.websocket.spring;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;

/**
 * @author Tang
 * @classname SimpleServer
 * @description [  ]
 * @date 2022/3/21 21:39
 */
public class SimpleServer extends WebSocketServer {

    public SimpleServer(InetSocketAddress address) {
        super(address);
    }

    @Override
    public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
        webSocket.send("Welcome to the server!");
        System.out.println("new connection to " + webSocket.getRemoteSocketAddress() + ",path: " + clientHandshake.getResourceDescriptor());
    }

    @Override
    public void onMessage(WebSocket webSocket, String message) {
        System.out.println("received message from " + webSocket.getRemoteSocketAddress() + ": " + message);
        webSocket.send(message);
    }

    @Override
    public void onClose(WebSocket webSocket, int code, String reason, boolean b) {
        System.out.println("closed " + webSocket.getRemoteSocketAddress() + " with exit code " + code + " additional info: " + reason);
    }

    @Override
    public void onError(WebSocket webSocket, Exception ex) {
        System.err.println("an error occurred on connection " + webSocket.getRemoteSocketAddress()  + ":" + ex);
    }

    public static void main(String[] args) {
        String host = "127.0.0.1";
        int port = 8887;

        WebSocketServer server = new SimpleServer(new InetSocketAddress(host, port));
        server.run();
    }

}